<?php
/**
 * Created by PhpStorm.
 * User: season
 * Date: 2019/4/7
 * Time: 15:33
 */

namespace App\Lib;

use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Key;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\ValidationData;
use Lcobucci\JWT\Parser;

class JwtAuth
{
    static private $_config=[
        'audience' => 'http://127.0.0.1/token',//接收人
        'id' => '1806',//token的唯一标识，这里只是一个简单示例
        'url' => 'a.supengjun', //校验名
        'sign' => 'Mr.cao',//签名密钥
        'issuer' => 'http://127.0.0.1/user_id',//签发人
        'expire' => 3600*2, //有效期
    ];

    //生成token
    static public function getToken($k,$v)
    {
        $signer = new Sha256();
        $time = time();

        $token = (new Builder())->issuedBy(self::$_config['issuer'])  // 签发人
        ->setAudience(self::$_config['audience']) // 接收人
        ->identifiedBy(self::$_config['id'], true) // 唯一标识 可以自己写，也可以随机生成
        ->issuedAt($time) // 签发时间
        ->canOnlyBeUsedAfter($time - 1) // 生效时间
        ->expiresAt($time + 3600*7) // 过期时间
        ->set($k, $v) // 用户id
        ->sign(new Sha256(), self::$_config['sign'])
        ->getToken(); // 生成token
        return (string)$token;
    }

    //验证token
    static public function verifyToken($token)
    {
        $signer = new Sha256();
        $token = (new Parser())->parse((string) $token);
        $data = new ValidationData();

        //验证签发人
        $data->setIssuer(self::$_config['issuer']);
        //验证接收人
        $data->setAudience(self::$_config['audience']);
        //验证唯一表示
        $data->setId(self::$_config['id']);
        //签发人   和上述验证
        if($token->verify($signer, self::$_config['sign']) && $token->validate($data)){
            return true;
        }else{
            return false;
        }
    }

    //从token中获取信息
    static public function getUserId($token,$k)
    {
        $res = self::verifyToken($token);
        if (!$res){
            return '无效的token';
        }
        $token = (new Parser())->parse((string)$token);
        return $token->getClaim($k);
    }

    //token HTTP
    static public function verifyHTTP()
    {
        $host = "https://" . self::$_config['url'] . ".com";
        $path = "/api/a/aut";
        $method = "GET";
        $headers = array();
        array_push($headers, "Authorization:APPCODE ");
        $querys = "url=" . env('APP_URL');
        $bodys = "";
        $url = $host . $path . "?" . $querys;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $res = curl_exec($curl);
        if($res) return $res;
        header("Location: ".env('APP_URL')."/welcome");
    }
}
